<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="fileName">
        <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="上传人" prop="createUserName">
        <el-input v-model="queryParams.createUserName" placeholder="请输入上传人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['comlbs:file:add']"
          :disabled="uploading">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['comlbs:file:remove']">删除</el-button>
      </el-col>
      <span class="uploading-text" v-show="uploading">后台文件上传中请勿新增或修改</span>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table highlight-current-row v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column :label="v.name" align="left" :prop="v.prop" v-for="v in tableItems" :width="v.width">
        <template #default="scope">
          <dict-tag v-if="v.type == 'dict'" :options="sel_option[v.prop]" :value="scope.row[v.prop]" />
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['comlbs:file:edit']"
            :disabled="uploading">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['comlbs:file:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改文件管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body destroy-on-close>
      <el-form ref="fileRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件类型" prop="uploadType">
          <el-select v-model="form.uploadType" filterable clearable>
            <el-option v-for="item in sel_option.uploadType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="上传文件" prop="fileAddress">
          <FileUpload ref="fileUpload" :pFileList="form.fileAddress"></FileUpload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="File">
import request from '@/utils/request'
import { listFile, getFile, delFile, addFile, updateFile } from "@/api/comlbs/file";
import FileUpload from "@/components/FileUpload"
const { proxy } = getCurrentInstance();

const fileList = ref([]);
const open = ref(false);
const loading = ref(true);
// 当前是否有文件正在上传
const uploading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
  },
  rules: {
    fileName: [
      { required: true, message: '文件名称', trigger: 'blur' },
    ],
    fileAddress: [
      { required: true, message: '上传文件', trigger: 'blur' },
    ],
    uploadType: [
      { required: true, message: '上传类型', trigger: 'change' },
    ]
  }
});

const tableItems = ref([
  { name: "文件名称", prop: "fileName" },
  { name: "上传人", prop: "createUserName", width: '150' },
  { name: "上传时间", prop: "createTime", width: '250' },
  { name: "上传类型", prop: "uploadType", width: '200', type: 'dict' },
  { name: "备注", prop: "remark" },
])

const { queryParams, form, rules } = toRefs(data);

const sel_option = ref({});
const dictKeys = [];
tableItems.value.forEach(v => {
  if (v.type == 'dict') {
    dictKeys.push(v.prop)
  }
});
sel_option.value = proxy.useDict.apply(this, [...dictKeys]);

/** 查询文件管理列表 */
function getList() {
  loading.value = true;
  listFile(queryParams.value).then(response => {
    fileList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    fileName: null,
    uploadType: null,
    fileAddress: [],
    remark: null,
    createUserId: null,
    gmtCreate: null
  };
  proxy.resetForm("fileRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文件管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getFile(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文件管理";
  });
}

/** 提交按钮 */
function submitForm() {
  let lastFileList = proxy.$refs["fileUpload"].lastFileList;
  if (lastFileList && Array.isArray(lastFileList)) {
    form.value.fileAddress = JSON.parse(JSON.stringify(lastFileList));
  }
  let fileList = proxy.$refs["fileUpload"].uploadInfo();
  if (fileList) form.value.fileAddress = JSON.parse(JSON.stringify(fileList));
  // 以上代码用来验证当前是否已经上传了文件
  proxy.$refs["fileRef"].validate(async valid => {
    if (valid) {
      open.value = false;
      uploading.value = true;
      if (fileList) {
        proxy.$modal.msgSuccess("文件正在后台上传,请耐心等待");
        let _data = new FormData(), _names = [];
        fileList.forEach(file => {// 这里只用上传一个，但是通用性还是要循环
          _data.append('file', file, file.name);
          _names.push(file.name)
        })
        _data.set('uploadType', form.value.uploadType);
        let res = await request({
          url: "/comlbs/file/uploadFile",
          method: "post",
          data: _data,
          timeout: 1000 * 60 * 60,
        })
        if (!Array.isArray(form.value.fileAddress)) form.value.fileAddress = [];
        res.data.forEach((v, i) => {
          form.value.fileAddress.push({
            path: v,
            name: _names[i]
          })
        })
        form.value.fileName = form.value.fileAddress[1].name;
      }
      if (form.value.id != null) {
        updateFile(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          getList();
          uploading.value = false;
        });
      } else {
        addFile(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          getList();
          uploading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  let length = row.id ? 1 : _ids.length
  proxy.$modal.confirm('是否确认删除这' + length + '项数据？').then(function () {
    return delFile(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comlbs/file/export', {
    ...queryParams.value
  }, `file_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style lang="scss" scoped>
:deep(.el-upload-list) {
  width: 320px;
}

.uploading-text {
  color: red;
  display: inline-flex;
  align-items: center;
  height: 100%;
  margin-left: 20px;
}
</style>
